﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;
using WeatherHistory.Shared.Helpers;

namespace WeatherHistory.Api.CommandsQueries.Commands.Accounts.Update;

public class UpdateAccountsCommandHandler : IRequestHandler<UpdateAccountsCommandRequest, UpdateAccountsCommandResponse>
{
    private readonly IAccountRepository _accountRepository;
    private readonly IMapper _mapper;

    public UpdateAccountsCommandHandler(IAccountRepository accountRepository, IMapper mapper)
    {
        _accountRepository = accountRepository;
        _mapper = mapper;
    }

    public async Task<UpdateAccountsCommandResponse> Handle(UpdateAccountsCommandRequest request, CancellationToken cancellationToken)
    {
        var emailRegistered = await _accountRepository.AnyAsync(x => x.Email == request.Email.ToLower() && x.Id != request.AccountId, cancellationToken);
        if (emailRegistered) throw new ConflictException("Пользователь с таким email уже зарегистрирован");

        var account = await _accountRepository.FirstOrDefaultAsync(x => x.Id == request.AccountId, cancellationToken);
        account.FirstName = request.FirstName;
        account.LastName = request.LastName;
        account.Email = request.Email.ToLower();
        account.PasswordHash = SecurityHelper.ComputeSha256Hash(request.Password);

        await _accountRepository.UpdateAsync(account, cancellationToken);

        return _mapper.Map<UpdateAccountsCommandResponse>(account);
    }
}